package com.sws.worktive.facebook;

import java.io.UnsupportedEncodingException;

import org.brickred.socialauth.android.DialogListener;
import org.brickred.socialauth.android.SocialAuthAdapter;
import org.brickred.socialauth.android.SocialAuthAdapter.Provider;
import org.brickred.socialauth.android.SocialAuthError;
import org.brickred.socialauth.android.SocialAuthListener;

import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;

public class FaceBookHandler{
	private String message;
	private String logoUrl;
	private String appWebSite;
	private Context mContext;
	
	private SocialAuthAdapter  socialAuthAdapter;
	
	public FaceBookHandler(String message, String logoUrl, String appWebsite, Context context){
		this.message = message;
		this.logoUrl = logoUrl;
		this.appWebSite = appWebsite;
		this.mContext = context;
	}
	
	public void sendFaceBookFeed(){
		socialAuthAdapter = new SocialAuthAdapter(createFaceBookDialogListener());
		
		socialAuthAdapter.authorize(mContext, Provider.FACEBOOK);
	}
	
	private DialogListener createFaceBookDialogListener(){
		return new DialogListener() {
			
			@Override
			public void onError(SocialAuthError arg0) {
				String errorMessage = arg0.getMessage();
				if (errorMessage != null && errorMessage.length() >0) {
					Toast.makeText(mContext, errorMessage, Toast.LENGTH_SHORT).show();
				}else {
					Toast.makeText(mContext, mContext.getString(com.sws.worktive.R.string.something_went_wrong), Toast.LENGTH_SHORT).show();
				}
			}
			
			@Override
			public void onComplete(Bundle arg0) {
					try {
						socialAuthAdapter.updateStory(
								message,
								"",
								"",
								"",
								appWebSite, 
								logoUrl,
								createSocialAuthListener());
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
						Toast.makeText(mContext, mContext.getString(com.sws.worktive.R.string.something_went_wrong), Toast.LENGTH_SHORT).show();
					}
				
			}
			
			@Override
			public void onCancel() {
			}
			
			@Override
			public void onBack() {
			}
		};
	}
	
	private SocialAuthListener<Integer> createSocialAuthListener(){
		return new SocialAuthListener<Integer>() {

			@Override
			public void onError(SocialAuthError arg0) {
			}

			@Override
			public void onExecute(String provider, Integer arg1) {
				Integer status = arg1;
				if (status.intValue() == 200 || status.intValue() == 201 || status.intValue() == 204)
					Toast.makeText(mContext, mContext.getString(com.sws.worktive.R.string.gain_one_credit_message), Toast.LENGTH_SHORT).show();
				else
					Toast.makeText(mContext, mContext.getString(com.sws.worktive.R.string.something_went_wrong), Toast.LENGTH_SHORT).show();
			}
			
		};
	}
}
